﻿using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Equipment.Select;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.ProjectMaintenance
{
    /// <summary>
    /// 项目维护编辑窗体
    /// </summary>
    public partial class ProjectMaintenanceEditForm : DevExpress.XtraEditors.XtraForm
    {
        public ProjectMaintenanceEditForm()
        {
            InitializeComponent();
            // 确保事件绑定，先移除可能的重复绑定
            ValueType.SelectedIndexChanged -= ValueType_SelectedIndexChanged;
            ValueType.SelectedIndexChanged += ValueType_SelectedIndexChanged;

            System.Diagnostics.Debug.WriteLine("编辑窗体已初始化，事件已绑定");
        }
        /// <summary>
        /// 项目维护编号
        /// </summary>
        private long Id { get; set; }
        /// <summary>
        /// 回显项目维护数据
        /// </summary>
        public void GetProjectMaintenanceData(ProjectMaintenanceOutput projectMaintenanceOutput)
        {
            try
            {
                // 保存Id
                Id = projectMaintenanceOutput.Id;

                // 设置基础字段
                ProjectMaintenanceName.Text = projectMaintenanceOutput.ProjectMaintenanceName;
                CheckoutWay.EditValue = projectMaintenanceOutput.CheckoutWay;

                // 先设置判断基准和最大最小值
                Criterion.Text = projectMaintenanceOutput.Criterion;
                ProjectMaintenanceMinNum.Text = projectMaintenanceOutput.ProjectMaintenanceMinNum.ToString();
                ProjectMaintenanceMaxNum.Text = projectMaintenanceOutput.ProjectMaintenanceMaxNum.ToString();

                // 显式设置控件可见性（先设置为默认状态，后面会再触发更新）
                labelControl4.Visible = true; // 最小值
                ProjectMaintenanceMinNum.Visible = true;
                labelControl5.Visible = true; // 最大值
                ProjectMaintenanceMaxNum.Visible = true;
                labelControl6.Visible = false; // 判断基准
                Criterion.Visible = false;

                // 直接通过索引设置RadioGroup值
                switch (projectMaintenanceOutput.ValueType)
                {
                    case "数值":
                        ValueType.SelectedIndex = 0;
                        break;
                    case "布尔":
                        ValueType.SelectedIndex = 1;
                        break;
                    case "文本":
                        ValueType.SelectedIndex = 2;
                        break;
                    default:
                        ValueType.SelectedIndex = 0; // 默认为数值
                        break;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"数据回显错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Diagnostics.Debug.WriteLine($"数据回显异常: {ex.Message}\n{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 获取检验方式数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProjectMaintenanceEditForm_Load(object sender, EventArgs e)
        {
            // 设置检验方式数据源
            List<CheckoutWayOutput> checkoutWayOutputs = new List<CheckoutWayOutput>()
            {
               new CheckoutWayOutput() { Id = 1, CheckoutWayName = "目视" },
               new CheckoutWayOutput() { Id = 2, CheckoutWayName = "擦拭" },
               new CheckoutWayOutput() { Id = 3, CheckoutWayName = "仪表测试" }
            };

            // 设备数据源
            CheckoutWay.Properties.DataSource = checkoutWayOutputs;
            CheckoutWay.Properties.DisplayMember = "CheckoutWayName";
            CheckoutWay.Properties.ValueMember = "Id";

            // 设置下拉列表的列
            CheckoutWay.Properties.Columns.Clear();
            CheckoutWay.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CheckoutWayName", "检验方式名称"));

            CheckoutWay.Properties.NullText = "请选择检验方式";

            System.Diagnostics.Debug.WriteLine("编辑窗体已加载");
        }

        /// <summary>
        /// 修改项目维护点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void UpdateProjectMaintenanceButton1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ProjectMaintenanceName.Text))
            {
                XtraMessageBox.Show("项目维护名称不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ProjectMaintenanceName.Focus();
                return;
            }

            if (CheckoutWay.EditValue == null)
            {
                XtraMessageBox.Show("请选择检验方式", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                CheckoutWay.Focus();
                return;
            }

            if (ValueType.SelectedIndex < 0)
            {
                XtraMessageBox.Show("请选择值类型", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ValueType.Focus();
                return;
            }

            // [添加] 创建数据对象
            ProjectMaintenanceOutput output = new ProjectMaintenanceOutput();
            output.Id = Id;
            output.ProjectMaintenanceName = ProjectMaintenanceName.Text;
            output.Criterion = Criterion.Text;
            if (ValueType.SelectedIndex == 0) // 数值类型
            {
                // 只有数值类型才需要转换最大值和最小值
                try
                {
                    output.ProjectMaintenanceMaxNum = Convert.ToInt32(ProjectMaintenanceMaxNum.Text);
                    output.ProjectMaintenanceMinNum = Convert.ToInt32(ProjectMaintenanceMinNum.Text);
                }
                catch (FormatException)
                {
                    XtraMessageBox.Show("最大值或最小值格式不正确，请输入有效的整数", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            else // 布尔或文本类型
            {
                // 对于布尔或文本类型，直接设置为0
                output.ProjectMaintenanceMaxNum = 0;
                output.ProjectMaintenanceMinNum = 0;
            }
            output.CheckoutWay = Convert.ToInt32(CheckoutWay.EditValue);
            // [修改] 将ValueType.SelectedIndex转换为对应的字符串值
            output.ValueType = ValueType.SelectedIndex == 0 ? "数值" :
                              (ValueType.SelectedIndex == 1 ? "布尔" : "文本");
            output.CreatedBy = "admin";
            output.CreatedTime = DateTime.Now;
            output.UpdatedBy = "admin";
            output.UpdatedTime = DateTime.Now;

            // [修改] 根据值类型设置不同字段
            if (ValueType.SelectedIndex == 0) // 数值类型
            {
                // 验证并设置最小值
                if (string.IsNullOrWhiteSpace(ProjectMaintenanceMinNum.Text))
                {
                    XtraMessageBox.Show("最小值不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMinNum.Focus();
                    return;
                }

                if (!int.TryParse(ProjectMaintenanceMinNum.Text.Trim(), out int minNum))
                {
                    XtraMessageBox.Show("最小值必须是有效的整数", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMinNum.Focus();
                    return;
                }

                // 验证并设置最大值
                if (string.IsNullOrWhiteSpace(ProjectMaintenanceMaxNum.Text))
                {
                    XtraMessageBox.Show("最大值不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMaxNum.Focus();
                    return;
                }

                if (!int.TryParse(ProjectMaintenanceMaxNum.Text.Trim(), out int maxNum))
                {
                    XtraMessageBox.Show("最大值必须是有效的整数", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMaxNum.Focus();
                    return;
                }

                if (minNum >= maxNum)
                {
                    XtraMessageBox.Show("最小值必须小于最大值", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMinNum.Focus();
                    return;
                }

                output.ProjectMaintenanceMinNum = minNum;
                output.ProjectMaintenanceMaxNum = maxNum;
                output.Criterion = string.Empty;
            }
            else // 布尔或文本类型
            {
                // 验证判断基准
                if (string.IsNullOrWhiteSpace(Criterion.Text))
                {
                    XtraMessageBox.Show("判断基准不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Criterion.Focus();
                    return;
                }

                // 判断基准长度验证
                if (Criterion.Text.Length > 50)
                {
                    XtraMessageBox.Show("判断基准不能超过50个字符", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Criterion.Focus();
                    return;
                }

                output.ProjectMaintenanceMinNum = 0;
                output.ProjectMaintenanceMaxNum = 0;
                output.Criterion = Criterion.Text;
            }



            try
            {
                // [添加] 显示等待光标
                Cursor.Current = Cursors.WaitCursor;

                // [修改] 发送更新请求
                using (var client = new HttpClient())
                {
                    // 序列化对象为JSON
                    var json = JsonConvert.SerializeObject(output);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // [修改] 发送PUT请求而非POST
                    var response = await client.PutAsync("http://47.110.243.157:5229/api/ProjectMaintenance/UpdateProjectMaintenance", content);

                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("更新成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"更新失败: {response.ReasonPhrase}\n详细信息: {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // [添加] 恢复默认光标
                Cursor.Current = Cursors.Default;
            }


        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ColseButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 值类型选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValueType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int selectedIndex = ValueType.SelectedIndex;
                System.Diagnostics.Debug.WriteLine($"值类型变更事件: 当前选择索引={selectedIndex}");

                if (selectedIndex == 0) // 数值
                {
                    // 显示最小值和最大值控件
                    labelControl4.Visible = true;
                    ProjectMaintenanceMinNum.Visible = true;
                    labelControl5.Visible = true;
                    ProjectMaintenanceMaxNum.Visible = true;

                    // 隐藏判断基准控件
                    labelControl6.Visible = false;
                    Criterion.Visible = false;
                }
                else // 布尔或文本
                {
                    // 隐藏最小值和最大值控件
                    labelControl4.Visible = false;
                    ProjectMaintenanceMinNum.Visible = false;
                    labelControl5.Visible = false;
                    ProjectMaintenanceMaxNum.Visible = false;

                    // 显示判断基准控件
                    labelControl6.Visible = true;
                    Criterion.Visible = true;
                }

                // 强制刷新界面
                this.Update();

                System.Diagnostics.Debug.WriteLine($"控件可见性设置完成: 最大值可见={ProjectMaintenanceMaxNum.Visible}, 判断基准可见={Criterion.Visible}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"值类型变更事件异常: {ex.Message}");
                XtraMessageBox.Show($"切换值类型时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}